import axios, { AxiosPromise } from 'axios'

const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 200000,
})

request.interceptors.request.use(config => {
  if (!config.headers) config.headers = {}
  return config
})

request.interceptors.response.use(
  response => {
    const code = Number.parseFloat(response.data?.code)
    // 链接成功
    if (code === 200) {
      return response.data
    }
    // onlyNotify(response.data?.message ?? '网络服务出错')
    return Promise.reject(response.data)
  },
  error => {
    // onlyNotify(error?.response?.data?.message ?? '网络服务出错')
    return Promise.reject(error)
  },
)

/* 以下是几个常用method的快速使用封装 */
export function getRequest<T = any>(url: string): AxiosPromise<T> {
  return request({
    url,
    method: 'get',
  })
}

export function postRequest<R = any, T = any>(
  url: string,
  data?: T,
): AxiosPromise<R> {
  return request({
    url,
    method: 'post',
    data,
  })
}

export function deleteRequest<R = any, T = any>(
  url: string,
  data?: T,
): AxiosPromise<R> {
  return request({
    url,
    method: 'delete',
    data,
  })
}

export function patchRequest<R = any, T = any>(
  url: string,
  data?: T,
): AxiosPromise<R> {
  return request({
    url,
    method: 'patch',
    data,
  })
}

export function putRequest<R = any, T = any>(
  url: string,
  data?: T,
): AxiosPromise<R> {
  return request({
    url,
    method: 'put',
    data,
  })
}

export default request
